#include <iostream>
#include <string>
#include <error.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <poll.h>

class Sock
{
    public:
    static int Socket()
    {
        int listen_sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if(listen_sockfd == -1)
        {
            fprintf(stderr, "socket: %s\n", strerror(errno));
            exit(2);
        }
        else
        {
            return listen_sockfd;
        }
    }

    static void Bind(int listen_sockfd, uint16_t port)
    {
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;
        if(bind(listen_sockfd, reinterpret_cast<const sockaddr*>(&local), sizeof(local)) == -1)
        {
            fprintf(stderr, "Bind: %s\n", strerror(errno));
            exit(3);
        }
        else
        {
            fprintf(stdout, "Bind succed!\n");
        }
    }

    static void Listen(int listen_sockfd)
    {
const int backlog = 5;
        if(listen(listen_sockfd, backlog) == -1)
        {
            fprintf(stderr, "Listen: %s\n", strerror(errno));
            exit(4);
        }
        else
        {
            fprintf(stdout, "Listen succed!\n");
        }
    }

    static int Accept(int listen_sockfd)
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        int fd = accept(listen_sockfd, reinterpret_cast<sockaddr*>(&peer), &len);
        if(fd == -1)
        {
            fprintf(stderr, "Accept: %s\n", strerror(errno));
            exit(5);
        }
        else
        {
            fprintf(stdout, "Accept succed!\n");
            return fd;
        }
    }
};